package leetcode.每日一题.链表;

import leetcode.util.CommonUtils;
import leetcode.剑指offer.pojo.ListNode;
import org.junit.Test;

/**
 * @author ：zsy
 * @date ：Created 2023/1/30 7:18 PM
 * @description：
 */
public class 合并两个链表 {
    @Test
    public void test() {
        ListNode listNode = new Solution().mergeInBetween(CommonUtils.transferArrToListNode(new int[]{0, 1, 2, 3, 4, 5}),
                3, 4, CommonUtils.transferArrToListNode(new int[]{1000000, 1000001, 1000002}));
        CommonUtils.printListNode(listNode);
    }

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
            ListNode tmp = list1;
            b = b - a + 2;
            while (--a > 0) {
                tmp = tmp.next;
            }
            ListNode prev = tmp;
            ListNode next = list2;
            while (next.next != null) {
                next = next.next;
            }
            while (--b >= 0) {
                tmp = tmp.next;
            }
            prev.next = list2;
            next.next = tmp;
            return list1;
        }
    }
}
